$(document).ready(function(){
	$('.spinnerExample').spinner({min:1});
	var goodsId = $("#goods_id").val();
	var skuId = $("#sku_id").val();
	//是否赠品
	var isGift = $("#sku_state").val()==3; 
	//缺货标识
	var outOfStockFlag = false;
	//没有选择全部规格 标识
	var notFullChooseflag = false;
	//请求总库存
	$.ajax({
		url:appPath+'/goodsSku/getInventoryAndIncreaseClick.json',
		type:'post',
		dataType:'json',
		data:{"goodsId":goodsId,"skuId":skuId},
		success:function(inventory){
			if(inventory<=0){
				outOfStockFlag = true;
				disabledOptionBtns();
			}
			$("#sku_inventory").val(inventory);
			$("#sku_inventory_em").text(inventory);
		},
		error:function(){
			//$.alert("系统异常!");
		}
	});	
	//获取价格列表
	$.ajax({
		url:appPath+'/goodsSku/getSkuPrices.htm',
		type:'post',
		dataType:'html',
		data:{"skuId":skuId,"token":$.cookie("token")},
		success:function(skuPricesInfo){
			$("#sku_prices_div").html(skuPricesInfo);
		},
		error:function(){
			//$.alert("系统异常!");
		}
	});	
	// 图片上下滚动
	//var count = $("#imageMenu li").length - 5; /* 显示 6 个 li标签内容 */
	var count = $("#imageMenu li").length ;
	var interval = $("#imageMenu li:first").width();
	var curIndex = 0;
	
	$('.scrollbutton').click(function(){
//		if(curIndex>=count-9){
//			return false;
//		}
		if( $(this).hasClass('disabled') ) return false;
		if ($(this).hasClass('smallImgUp')) {
			--curIndex;
		}else{ 
			if(curIndex+9>=count){
				return false;
			}
			++curIndex;
		}
		
		$('.scrollbutton').removeClass('disabled');
		if (curIndex == 0) $('.smallImgUp').addClass('disabled');
		if (curIndex == count-1) $('.smallImgDown').addClass('disabled');
		
		$("#imageMenu ul").stop(false, true).animate({"marginLeft" : -curIndex*interval + "px"}, 600);
	});	
//解决 ie6 select框 问题
	$.fn.decorateIframe = function(options) {
		if ($.browser.msie && $.browser.version < 7) {
			var opts = $.extend({}, $.fn.decorateIframe.defaults, options);
			$(this).each(function() {
				var $myThis = $(this);
				//创建一个IFRAME
				var divIframe = $("<iframe />");
				divIframe.attr("id", opts.iframeId);
				divIframe.css("position", "absolute");
				divIframe.css("display", "none");
				divIframe.css("display", "block");
				divIframe.css("z-index", opts.iframeZIndex);
				divIframe.css("border");
				divIframe.css("top", "0");
				divIframe.css("left", "0");
				if (opts.width == 0) {
					divIframe.css("width", $myThis.width() + parseInt($myThis.css("padding")) * 2 + "px");
				}
				if (opts.height == 0) {
					divIframe.css("height", $myThis.height() + parseInt($myThis.css("padding")) * 2 + "px");
				}
				divIframe.css("filter", "mask(color=#fff)");
				$myThis.append(divIframe);
			});
		}
	}
	$.fn.decorateIframe.defaults = {
			iframeId: "decorateIframe1",
			iframeZIndex: -1,
			width: 0,
			height: 0
	}
//放大镜视窗
	$("#bigView").decorateIframe();
//点击到中图
	var midChangeHandler = null;
	
	$("#imageMenu li img").bind("click", function(){
		if ($(this).attr("id") != "onlickImg") {
			midChange($(this).attr("src").replace("small", "mid"));
			$("#imageMenu li").removeAttr("id");
			$(this).parent().attr("id", "onlickImg");
		}
	}).bind("mouseover", function(){
		if ($(this).attr("id") != "onlickImg") {
			window.clearTimeout(midChangeHandler);
			midChange($(this).attr("src").replace("small", "mid"));
			$(this).css({ "border": "3px solid #959595" });
		}
	}).bind("mouseout", function(){
		if($(this).attr("id") != "onlickImg"){
			$(this).removeAttr("style");
			midChangeHandler = window.setTimeout(function(){
				midChange($("#onlickImg img").attr("src").replace("small", "mid"));
			}, 1000);
		}
	});
	function midChange(src) {
		$("#midimg").attr("src", src).load(function() {
			changeViewImg();
		});
	}
//大视窗看图
	function mouseover(e) {
		if ($("#winSelector").css("display") == "none") {
			$("#winSelector,#bigView").show();
		}
		$("#winSelector").css(fixedPosition(e));
		e.stopPropagation();
	}
	function mouseOut(e) {
		if ($("#winSelector").css("display") != "none") {
			$("#winSelector,#bigView").hide();
		}
		e.stopPropagation();
	}
	$("#midimg").mouseover(mouseover); //中图事件
	$("#midimg,#winSelector").mousemove(mouseover).mouseout(mouseOut); //选择器事件
	
	var $divWidth = $("#winSelector").width(); //选择器宽度
	var $divHeight = $("#winSelector").height(); //选择器高度
	var $imgWidth = $("#midimg").width(); //中图宽度
	var $imgHeight = $("#midimg").height(); //中图高度
	var $viewImgWidth = $viewImgHeight = $height = null; //IE加载后才能得到 大图宽度 大图高度 大图视窗高度
	
	function changeViewImg() {
		$("#bigView img").attr("src", $("#midimg").attr("src").replace("mid", "big"));
	}
	changeViewImg();
	$("#bigView").scrollLeft(0).scrollTop(0);
	function fixedPosition(e) {
		if (e == null) {
			return;
		}
		var $imgLeft = $("#midimg").offset().left; //中图左边距
		var $imgTop = $("#midimg").offset().top; //中图上边距
		X = e.pageX - $imgLeft - $divWidth / 2; //selector顶点坐标 X
		Y = e.pageY - $imgTop - $divHeight / 2; //selector顶点坐标 Y
		X = X < 0 ? 0 : X;
		Y = Y < 0 ? 0 : Y;
		X = X + $divWidth > $imgWidth ? $imgWidth - $divWidth : X;
		Y = Y + $divHeight > $imgHeight ? $imgHeight - $divHeight : Y;
		
		if ($viewImgWidth == null) {
			$viewImgWidth = $("#bigView img").outerWidth();
			$viewImgHeight = $("#bigView img").height();
			if ($viewImgWidth < 200 || $viewImgHeight < 200) {
				$viewImgWidth = $viewImgHeight = 800;
			}
			$height = $divHeight * $viewImgHeight / $imgHeight;
			$("#bigView").width($divWidth * $viewImgWidth / $imgWidth);
			$("#bigView").height($height);
		}
		var scrollX = X * $viewImgWidth / $imgWidth;
		var scrollY = Y * $viewImgHeight / $imgHeight;
		$("#bigView img").css({ "left": scrollX * -1, "top": scrollY * -1 });
		$("#bigView").css({ "top": 320, "left": $(".preview").offset().left + $(".preview").width() + 15 });
		
		return { left: X, top: Y };
	}

	//规格组合
	var skuCombinations = $("#skuCombinationsStr").val();
	
	var skuCombinationsJson = null;
	if(skuCombinations!=null&&skuCombinations!=""){
		skuCombinationsJson = eval("("+skuCombinations+")")
	}
	//当前规格
	var skuCombina = $("#goodsSkuSpecId").val();
	var combinaArr= skuCombina.split(";");
	//选中规格
	if(skuCombina){
		for(var i=0;i<combinaArr.length;i++){
			var speInfoArr = combinaArr[i].split(":");
			//var temId ="#spceValue"+speInfoArr[1];
			$("#spceValue"+speInfoArr[1]).addClass("yListrclickem");
		}
	}
	//规格map 每个规格值为key specId:valueId
	//var specMap = new Map();
	var specMap = {};
	if(skuCombinationsJson!=null){
		for(var skuCombina in skuCombinationsJson){
			var specCombina = skuCombinationsJson[skuCombina].specId;
			var specArr = specCombina.split(";");
			for(var spec in specArr){
				var key = specArr[spec];
				//var tem = specMap.get(key);
				var tem = specMap[key];
				if(tem==null||tem.length==0){
					tem = new Array();
				}
				tem.push(specCombina);
				//specMap.set(key,tem);
				specMap[key] = tem;
			}
		}
	}
	
	//disabled规格
	function checkAndDisableSpec(specValueDomId){
		var specId = $("#"+specValueDomId).parent().attr("specId");
		var specValueId = $("#"+specValueDomId).attr("specValueId");
		specCombinationKey = specId+":"+specValueId;
		//有效的sku规格组合
		//var temArr = specMap.get(specCombinationKey);
		var temArr = specMap[specCombinationKey];
		if(temArr==undefined||temArr==null){
			return false;
		}
		$("#"+specValueDomId).parent().removeClass("spec-hl-bg");
		$(".goodsSpec").each(function(){
			var temSpecId = $(this).attr("specId");
			//if (temSpecId != specId) {// 不是同一个规格分类才验证
			$(this).find(".spec_em").removeClass("em_disabled");
			var specArr = $(this).children("em");
			for (var i=0;i<specArr.length;i++ ) {
				var temSpecValueId = $(specArr[i]).attr("specValueId");
				var specStr = temSpecId + ":" + temSpecValueId;
				if (temSpecId != specId){
					var includeFlag = false;
					for ( var j=0;j<temArr.length;j++) {
						if (temArr[j].indexOf(specStr) > -1) {//有，直接退出循环
							includeFlag = true;
							break;
						}
					}
					if(!includeFlag){// 该规格值没有,设置disabaled
						$(specArr[i]).addClass("em_disabled");
						$(specArr[i]).removeClass("yListrclickem");
					}
				}else if(specMap[specStr]==undefined||specMap[specStr]==null){
					$(specArr[i]).addClass("em_disabled");
					$(specArr[i]).removeClass("yListrclickem");
				}
			}
			//}
		});
		//若无选中，整行
		$(".em_disabled").each(function(){
			if($(this).parent().find(".yListrclickem").length==0){//如果当前spec未选，设置
				$(this).parent().addClass("spec-hl-bg");
				outOfStockFlag = true;
			}
		});
		return true;
	}
	/**
	 * 规格点击事件
	 */
	function getSkuId(_this){
		notFullChooseflag = false;
		checkAndDisableSpec($(_this).attr("id"));
		$(_this).parent().children(".yListrclickem").removeClass("yListrclickem");
		$(_this).addClass("yListrclickem");
		//规格格式（规格类名id:规格值id;规格类名id:规格值id）
		var specCombinationStr ="";
		$(".goodsSpec").each(function(){
			if($(this).find(".yListrclickem").length==0){//有规格未选
				notFullChooseflag = true;
				disabledOptionBtns();
				return false;
			}
			var specId = $(this).attr("specId");
			var specValueId = $($(this).children(".yListrclickem")[0]).attr("specValueId");
			specCombinationStr+=specId+":"+specValueId+";";
		});
		if(notFullChooseflag){
			return false;
		}
		specCombinationStr = specCombinationStr.substr(0,specCombinationStr.length-1);
		var temArr = skuCombinations.split(specCombinationStr);
		if(temArr.length==1){//没有该规格,添加checkAndDisableSpec()方法后，这个判断永远进不了。
			disabledOptionBtns();
			//缺货标识
			outOfStockFlag = true;
			return ;
		}
		//$("#choosedSpecCombination").text(specCombinationNameStr);
		var temArr = temArr[0].split(",{");
		var idStr = temArr[temArr.length-1];
		var matchResult = idStr.match("\\d+");
		var skuId =matchResult[0];
		window.location = appPath+"/"+skuId+".htm";
	}
	
	function checkBuyNumGtInventory(){
		var inventory = $("#sku_inventory").val();
		var num = $("#goods_num").val();
		return inventory-num>=0;
	}
	
	/**
	 *加入购物车
	 */
	$("#save_in_cart").click(function(){
		if(isGift){
			$.alert("该商品为赠品，不能购买！");
			return false;
		}
		if(outOfStockFlag){
			$.alert("商品缺货，无法进行此操作！");
			return false;
		}
		if(notFullChooseflag){
			return false;
		}
		if(!checkBuyNumGtInventory()){
			$.alert("购买数量大于商品库存！");
			return false;
		}
		if(limitTimeFlag){
			$.alert("商品不在限购时段内！");
			return false;
		}
		var skuId = $("#sku_id").val();
		var num = $("#goods_num").val();
		var isBuy =0;
		//加入购物车 操作
		var optionType =1;
		modifyCartItemsCookie(skuId, num,isBuy, optionType);
		//更新购物数量
		var cartCount = calculateCartCount();
		$(".cart_count").text(cartCount);
	});
	
	/**
	 * 跳转购物车
	 */
	$("#cart_link").click(function(){
		var url = appPath+"/cart/list.htm";
		$(this).attr("href",url);
		
	});
	/**
	 * 单品购买
	 */
	$("#single_buy").click(function(){
		if(isGift){
			$.alert("该商品为赠品，不能购买！");
			return false;
		}
		if(outOfStockFlag){
			$.alert("商品缺货，无法进行此操作！");
			return false;
		}
		if(notFullChooseflag){
			return false;
		}
		if(!checkBuyNumGtInventory()){
			$.alert("购买数量大于商品库存！");
			return false;
		}
		if(limitTimeFlag){
			$.alert("商品不在限购时段内！");
			return false;
		}
		var url=appPath+"/order/preOrderInfo.htm";
		var skuId = $("#sku_id").val();
		var token = $.cookie("token");
		var temGoodsNum =$("#goods_num").val();
		//var singleBuyFlag=1;
		// cartId-skuId-num-isBuy-isDel
		var singleBuyInfo = "-"+skuId+"-"+temGoodsNum+"-"+1+"-0";
		self.location=url+"?token="+token+"&singleBuyFlag=1&singleBuyInfo="+singleBuyInfo;
	});
	//积分兑换
	$("#point_buy").click(function(){
		if(!isGift){
			$.alert("该商品不为积分兑换商品！");
			return false;
		}
		if(!checkBuyNumGtInventory()){
			$.alert("购买数量大于商品库存！");
			return false;
		}
		if(outOfStockFlag){
			$.alert("商品缺货，无法进行此操作！");
			return false;
		}
		if(limitTimeFlag){
			$.alert("商品不在限购时段内！");
			return false;
		}
		//判断用户积分
		var url=appPath+"/order/preOrderInfo.htm";
		var skuId = $("#sku_id").val();
		var token = $.cookie("token");
		var temGoodsNum =$("#goods_num").val();
		//var singleBuyFlag=1;
		// cartId-skuId-num-isBuy-isDel
		var singleBuyInfo = "-"+skuId+"-"+temGoodsNum+"-"+1+"-0";
		self.location=url+"?token="+token+"&singleBuyFlag=2&singleBuyInfo="+singleBuyInfo;
	});
	$(".spec_em.yListrclickem").each(function(){
		checkAndDisableSpec($(this).attr("id"));
	});
	$(".spec_em").click(function(){
		if($(this).hasClass("em_disabled")){
			return;
		}
		if($(this).hasClass("yListrclickem")){
			return;
		}
		getSkuId(this);
	});
	$("#page_div").myPagination({
		currPage : 1,
		pageCount : $("#pageCount").val(),
		pageSize : 10,
		ajax : {
			on : true,
			callback : 'getPagenation',
			url : appPath+'/comments/list.htm?goodsId='+goodsId,
			data:{
				page :$("#curPage").val()
			},
			dataType : 'html'
		}
	});	
	
	uParse('#goods_detail_div', {
	    rootPath: appPath+'/js/ueditor'
	})
	if($("#time_span").length>0){
		initTime = $("#goods_time_info_sec").val();
		limitState = $("#goods_time_info_state").val();
		//console.log(initTime);
		if(limitState!=3){
			if(limitState==1){//未开始
				limitTimeFlag = true;
			}
			startCalculateTime();
		}else{
			limitTimeFlag = true;
		}
		//var limitTimer  = setTimeout("startCalculateTime()",1000);
	}
});
//限时标志
var limitTimeFlag = false;
var initTime = 0;
var limitState = "";
var limitTimer ="";
/**
 * 限时购计时
 */
function startCalculateTime(){
	initTime = initTime -1000;
	var secs = Math.floor(initTime/1000);
	limitTimer = setTimeout("startCalculateTime()",1000);
	if(secs<=0){
		if(limitState==2){
			limitTimeFlag = true;
			clearTimeout(limitTimer);
			$(".limit_msg").text("抢购已结束");
		}
	}
	var mins = Math.floor(secs/60);
	var hours = Math.floor(mins/60);
	var days = Math.floor(hours/24);
	var timeStr = days+"天"+hours%24+"小时"+mins%60+"分钟"+secs%60+"秒";
	$("#time_span").text(timeStr);
}
//分页
function getPagenation(data){
	var div = $(data).find("#comment_div");
	$("#comment_div").html($(div[0]).html());
}
//tab页
function navigate_tabs(container, tab)
{	
	$(".b").css('display' , 'none');
	$(".c").css('display' , 'none');
	$(".a").css('display' , 'none');
	
	$("#first-tab").removeClass('buttonHover');
	$("#second-tab").removeClass('buttonHover');
	$("#third-tab").removeClass('buttonHover');
	
	$("#"+tab).addClass('buttonHover');
	$("."+container).show('slow');
}
$("#first-tab").addClass('buttonHover');
//添加收藏
function favoriteGoods(goodsId,skuId){
	$.ajax({
		url:appPath+'/favorites/save.html',
		type:'post',
		dataType:'json',
		data:{"goodsId":goodsId,"skuId":skuId,"token":$.cookie("token")},
		success:function(result){
			if(result.code=="-1"){
				var loginUrl=appPath+"/member/login.htm"; 
				self.location=loginUrl;
			}else if(result.code=="1"){//成功
				$.alert(result.msg);
			}else{//已收藏
				$.alert(result.msg);
			}
		},
		error:function(){
			$.alert("系统异常!");
		}
	});
}
function disabledOptionBtns(){
	$(".opt_btn").addClass("btn_disabled");
	
}
